/*
* vuex socket
* */
let websockInst = null
let timerSocket = -1
const utilSocket = {

  //初始化
  _init() {
    console.debug('   utilSocket.init')
    // 创建websocket连接 ws://ip:9527/spdsocket
    let socketUrl = `ws://${location.host}/api/spdsocket`
    websockInst = new WebSocket(socketUrl)
    // 监听打开
    websockInst.onopen = utilSocket.websockOpen
    // 监听关闭
    websockInst.onclose = utilSocket.websockClose
    //监听异常
    websockInst.onerror = utilSocket.websockError
    //监听服务器发送的消息
    websockInst.onmessage = utilSocket.onmessage
  },

  //初始化
  init(isTry = false) {
    if (isTry) {
      if (timerSocket != -1) {
        return
      }
      console.debug('%c   utilSocket.retry','color: #e37318;')
      timerSocket = setInterval(() =>{
        utilSocket._init(true)
      },1000 * 10)
      return
    }
    timerSocket = -1
    utilSocket._init(isTry)
  },
  websockOpen() {
    console.debug('%c   utilSocket.success','color: #2ba471;')
    if (timerSocket != -1) {
      try {
        clearInterval(timerSocket)
      }catch (e) {
      }
      timerSocket = -1
      console.debug('%c   utilSocket.retry.success','color: #e37318;')
    }
  },
  websockClose(event) {
    // console.error('utilSocket.websockClose', event)
    utilSocket.init(true)
  },
  websockError(event) {
    // console.error('utilSocket.websockError', event)
    utilSocket.init(true)
  },

  //socket接受到参数后执行
  onmessage(messageEvent) {
    console.info('utilSocket.onmessage', messageEvent)
    if (messageEvent && messageEvent.data) { //messageEvent.data 对应后台WebSocketMsgDTO.java
      let webSocketMsgDTO = JSON.parse(messageEvent.data)
      if (webSocketMsgDTO) {
        switch (webSocketMsgDTO.type) {
          case 'param_change': //参数变化
          {
            let typeSub = webSocketMsgDTO.typeSub
            if (typeSub) { //子类型
              switch (typeSub) {
                case 'user_msg':{ //用户站内消息
                  window.getInnerInbox()
                  break
                }
                case 'dict_data':{ //数据字典数据
                  //刷新参数等
                  global.utilVuex.syncAll(null, () => {
                    global.utilMessage.success('数据字典已刷新')
                  }, ['dictTypeList', 'dictData'])
                  break
                }
                case 'dict_type':{ //数据字典类型
                  //刷新参数等
                  global.utilVuex.syncAll(null, () => {
                    global.utilMessage.success('数据字典已刷新')
                  }, ['dictTypeList', 'dictData'],'数据字典已刷新')
                  break
                }
                case 'parameter':{ //系统参数
                  //刷新参数等
                  global.utilVuex.syncAll(null, () => {
                    global.utilMessage.success('系统参数已刷新')
                  }, ['parameterList'])
                  break
                }
              }
            }
            break
          }
          default:
            console.error('未实现的类型')
        }
      }
    }
  }
}
export default utilSocket
